package com.hxd.charitysystem.ui.activity

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import com.hjq.dialog.WaitDialog
import com.hxd.charitysystem.R
import com.hxd.charitysystem.adapter.GridImageAdapter
import com.hxd.charitysystem.base.common.MyActivity
import com.hxd.charitysystem.bean.NetBaseBean
import com.hxd.charitysystem.utils.L
import com.hxd.charitysystem.utils.ProjectUrl
import com.hxd.charitysystem.widget.FullyGridLayoutManager
import com.hxd.tabactivityfragment.util.GsonToBean
import com.kymjs.rxvolley.RxVolley
import com.kymjs.rxvolley.client.HttpCallback
import com.kymjs.rxvolley.client.HttpParams
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.vondear.rxtool.RxSPTool
import kotlinx.android.synthetic.main.activity_start_fundrais.*
import org.jetbrains.anko.startActivity
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


/**
 *  项目名：    CharitySystem
 *  包名：      com.hxd.charitysystem.ui.activity
 *  文件名:     StartFundraisingActivity
 *  创建者:     HXD
 *  创建时间:   2019/5/3 11:09
 *  描述:       发起筹款界面
 */

class StartFundraisingActivity : MyActivity() {

    private val selectList = ArrayList<LocalMedia>()
    private val adapter by lazy { GridImageAdapter(getActivity(), onAddPicClickListener) }
    private var manager: FullyGridLayoutManager? = null
    private val token by lazy { RxSPTool.getString(this, "token") }
    private var maxSelectNum = 9
    private val themeId by lazy { R.style.picture_default_style }
    private var imagesFile = ArrayList<File>()
    private var images = ArrayList<String>()
    private val projectWaitDialog by lazy { WaitDialog.Builder(this).setMessage("正在发布中...").show(); }
    private val imageWaitDialog by lazy { WaitDialog.Builder(this).setMessage("图片正在上传...").show(); }
    private var imageCount:Int = 0


    private val onAddPicClickListener: GridImageAdapter.onAddPicClickListener = GridImageAdapter.onAddPicClickListener {
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(this@StartFundraisingActivity)
            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .theme(themeId)//主题样式
            .maxSelectNum(maxSelectNum)// 最大图片选择数量 int
            .minSelectNum(1)// 最小选择数量 int
            .imageSpanCount(4)// 每行显示个数 int
            .selectionMode(PictureConfig.MULTIPLE)//多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
            .previewImage(true)// 是否可预览图片 true or false
            .enableCrop(false)// 是否裁剪 true or false
            .compress(false)// 是否压缩 true or false
            .glideOverride(160, 160)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
            .withAspectRatio(16, 9)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
            .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示 true or false
            .isGif(true)//是否显示gif图片 true or false
            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
            .circleDimmedLayer(false)// 是否圆形裁剪 true or false
            .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
            .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
            .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
            .forResult(PictureConfig.CHOOSE_REQUEST)//结果回调onActivityResult code
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_start_fundrais
    }

    override fun getTitleId(): Int {
        return R.id.tb_startFundrais_title
    }

    override fun initView() {

        manager = FullyGridLayoutManager(getActivity(), 4, GridLayoutManager.VERTICAL, false)
        recycler_fundrais_addImages.layoutManager = manager
        adapter.setList(selectList)
        adapter.setSelectMax(maxSelectNum)
        recycler_fundrais_addImages.adapter = adapter
        adapter.setOnItemClickListener { position, v ->
            val media = selectList[position]
            val pictureType = media.pictureType
            when (PictureMimeType.pictureToVideo(pictureType)) {
                1 ->
                    // 预览图片
                    PictureSelector.create(this@StartFundraisingActivity).themeStyle(themeId).openExternalPreview(
                        position,
                        selectList
                    )
                2 ->
                    // 预览视频
                    PictureSelector.create(this@StartFundraisingActivity).externalPictureVideo(media.path)
                3 ->
                    // 预览音频
                    PictureSelector.create(this@StartFundraisingActivity).externalPictureAudio(media.path)
            }
        }


        btn_startFundrais_commit.setOnClickListener {
            if(imagesFile.size > 0){
                imageWaitDialog
                imagesFile.let {
                    it.forEach {image ->
                        addImages(image)
                    }
                }
            }else{
                commit()
            }

        }
    }

    override fun initData() {

    }

    /**
     * 发布项目
     */
    private fun commit() {
        val targetAmount = et_fundrais_targetAmount.text.toString()
        val title = et_fundrais_title.text.toString()
        val desc = et_fundrais_desc.text.toString()
        val type = et_fundrais_illnessType.text.toString()
        val address = et_fundrais_address.text.toString()
        val params = HttpParams()
        params.putHeaders("token", token)
        params.put("title", title)
        params.put("desc", desc)
        params.put("targetAmount", targetAmount)
        params.put("type", type)
        params.put("address", address)

        if (images != null) {
            images.forEach { image ->
                params.put("assistantImages", image)
            }
        }
        projectWaitDialog
        RxVolley.post(ProjectUrl.postProject, params, object : HttpCallback() {
            override fun onSuccess(result: String?) {
                val data = GsonToBean.JsonToBean<NetBaseBean<String>>(result)
                projectWaitDialog.dismiss()
                if (data.status == 200) {
                    toast("项目发布成功！")
                    startActivity<MainActivity>()
                    finish()
                } else {
                    toast(data.msg)
                    L.i("项目发布失败 ： ${data.msg}")
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                projectWaitDialog.dismiss()
                L.i("commitFundrais errorNo : $errorNo, strMsg: $strMsg ")
            }
        })
    }

    /**
     * 多图上传
     */
    private fun addImages(file: File) {
        val params = HttpParams()
        params.put("image", file)
        RxVolley.post(ProjectUrl.publicImage, params, object : HttpCallback() {
            override fun onSuccess(result: String?) {
                val data = GsonToBean.JsonToBean<NetBaseBean<String>>(result)
                if (data.status == 200) {
                    L.i("图片上传成功！！！ ${data.msg}")
                    images.add(data.msg)
                    imageCount++
                    if(imageCount == imagesFile.size){
                        imageWaitDialog.dismiss()
                        commit()
                    }
                } else {
                    imageWaitDialog.dismiss()
                    commit()
                    L.i("图片上传失败！！！ ${data.msg}")
                }
            }

            override fun onFailure(errorNo: Int, strMsg: String?) {
                imageWaitDialog.dismiss()
                commit()
                L.i("postPublicImages errorNo:$errorNo, strMsg:$strMsg")
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode === Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片、视频、音频选择结果回调
                    val selectList = PictureSelector.obtainMultipleResult(data)
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList)
                    adapter.notifyDataSetChanged()
                    imagesFile.clear()
                    images.clear()
                    selectList.forEach { localMedia ->
                        //进行图片压缩
                        Luban.with(this).load(localMedia.path).ignoreBy(100)
                            .setCompressListener(object : OnCompressListener {
                                override fun onSuccess(file: File?) {
                                    imagesFile.add(file!!)
                                }


                                //当压缩过程出现问题时调用
                                override fun onError(e: Throwable?) {

                                }

                                //当压缩过程出现开始时
                                override fun onStart() {
                                }
                            }).launch()
                    }

                }
            }
        }
    }
}